//
//  UIImageView_public extension.swift
//  MyLibrary
//
//  Created by 周博 on 2020/7/16.
//  Copyright © 2020 ncit. All rights reserved.
//

import UIKit
import SDWebImage

public extension UIImageView {

    func sd_setImage(with urlString: String?, completed: ((UIImage?, Error?, SDImageCacheType, URL?) -> Void)? = nil) {

        if let url = URL(string: urlString ?? "") {
            self.sd_setImage(with: url, completed: completed)
        }
    }
    
    
    var gifPngName: String {
        get {
            return ""
        }
        set {
            
            if self.animationImages != nil {
                self.animationImages?.removeAll()
            }
            
            if newValue.count > 0 {
                
                // 1、加载gif图片，并转成Data类型
                guard let imgPath = Bundle.main.path(forResource: newValue + ".png", ofType: nil) else { return }
                loadGif(imgPath: imgPath)
            }
        }
    }

    var gifName: String {
        get {
            return ""
        }
        set {
            // 1、加载gif图片，并转成Data类型
            guard let imgPath = Bundle.main.path(forResource: newValue + ".gif", ofType: nil) else { return }
            loadGif(imgPath: imgPath)
        }
    }
    
    var imageName: String {
        get {
            return ""
        }
        set {
            if newValue.count > 0 {
                self.image = UIImage(named: newValue)
            }
        }
    }
    
    
    private func loadGif(imgPath: String) {
        guard let imgData = NSData(contentsOfFile: imgPath) else { return }
        
        // 2、从data中读取数据：将data转成CGImageSource对象
        guard let imgSource = CGImageSourceCreateWithData(imgData, nil) else {
            return
        }
        
        // 3、获取在CGImageSource中图片的个数
        let imgCount = CGImageSourceGetCount(imgSource)
        
        // 4、遍历所有图片
        var imgs = [UIImage]()
        var totalDuration: TimeInterval = 0
        for i in 0..<imgCount {
            // 4.1、取出图片
            guard let cgimg = CGImageSourceCreateImageAtIndex(imgSource, i, nil) else { continue }
            let img = UIImage(cgImage: cgimg)
            if i == 0 { // 保证执行完一次gif后不消失
                self.image = img
            }
            imgs.append(img)
            
            // 4.2、取出持续的时间
            guard let cf_properties = CGImageSourceCopyPropertiesAtIndex(imgSource, i, nil) else { continue }
            
            let properties = cf_properties as NSDictionary
            guard let dict = properties[kCGImagePropertyGIFDictionary] as? NSDictionary else { continue }
            guard let duration = dict[kCGImagePropertyGIFDelayTime] as? NSNumber else { continue }
            totalDuration += duration.doubleValue
        }
        
        // 5、设置imageView的属性
        self.animationImages = imgs
        self.animationDuration = totalDuration
        self.animationRepeatCount = 0  // 设置为0时无限执行
        
        // 6、开始播放
        self.startAnimating()
    }
    
}
